package com.yiyuan.common.search;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;
import org.wltea.analyzer.lucene.IKQueryParser;
import org.wltea.analyzer.lucene.IKSimilarity;

public class SearchManager {
	/**
	 * 查询
	 */
	@SuppressWarnings("unchecked")
	public static Map search(String keyword, int perPage,
			int startIndex, int endIndex) throws Exception {
	
		String field = "docContent";
		// 1、读取索引文件
		IndexReader reader = IndexReader.open(FSDirectory.open(new File(
				Constants.INDEX_DIR_PATH)), true);
		// 2、构造查询器
		Searcher searcher = new IndexSearcher(reader);
		// 3、构造分析器
		Analyzer analyzer = new IKAnalyzer();
		//在索引器中使用IKSimilarity相似度评估器
		searcher.setSimilarity(new IKSimilarity());
		// 4、查询解析
		Query query =IKQueryParser. parse(field, keyword);
		// 5、检索
		Map map = doPageSearch(searcher, query, analyzer, perPage,
				startIndex, endIndex);
		reader.close();
		return map;

	}
	// 分页搜索
	@SuppressWarnings("unchecked")
	public static Map doPageSearch(Searcher searcher, Query query,
			Analyzer analyzer, int hitsPerPage, int startIndex, int endIndex)
			throws IOException, InvalidTokenOffsetsException {
		
		Map map=new HashMap(); 
		List<DocObj> docList = new ArrayList<DocObj>();
		//首次查询结果
		TopScoreDocCollector collector = TopScoreDocCollector.create(
				10 * hitsPerPage, false);
		searcher.search(query, collector);
		ScoreDoc[] hits = collector.topDocs().scoreDocs;

		int numTotalHits = collector.getTotalHits();

		int end = Math.min(numTotalHits, endIndex);

		//如果请求的条数大于已查询出来的结果集数目，则扩大查询容量
		if (end > hits.length) {
			collector = TopScoreDocCollector.create(end, false);
			searcher.search(query, collector);
			hits = collector.topDocs().scoreDocs;
		}
		
		end = Math.min(hits.length, startIndex + hitsPerPage-1);

		for (int i = startIndex-1; i < end; i++) {
			Document doc = searcher.doc(hits[i].doc);
			DocObj docObj = new DocObj();
			docObj.setDocId(doc.get("docId"));
			docObj.setDocName(doc.get("docName"));
			docObj.setDocDesc(doc.get("docDesc"));
			docObj.setDocPath(doc.get("docPath"));
			docList.add(docObj);
			/* ******************高亮显示*************************** */
			// // 提取摘要，并对查询关键字高亮显示
			// SimpleHTMLFormatter format = new SimpleHTMLFormatter("<font
			// color=red>", "</font>");
			// // 高亮 ，计分器
			// Highlighter highlighter = new Highlighter(format, new
			// QueryScorer(query));
			// // 关键字附近字符串的截取，截取200个字符
			// Fragmenter fragmenter = new SimpleFragmenter(200);
			// highlighter.setTextFragmenter(fragmenter);
			// // 针对某个关键字的高亮以及截取
			// String content = doc.get("contents");
			// TokenStream content_tokenStream =
			// analyzer.tokenStream("content",new StringReader(content));
			// content = highlighter.getBestFragment(content_tokenStream,
			// content);
			/* ******************************************************* */
		}
		map.put("list", docList);
		map.put("totalRecord", numTotalHits+"");
		return map;
	}

}
